package com.mongodb;

import com.mongodb.model.Collection;
import com.mongodb.model.DataBase;
import com.mongodb.model.Root;
import com.mongodb.service.IMDataBaseService;
import com.mongodb.service.MDataBaseService;
import org.apache.log4j.Logger;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by chrhc on 2016/5/23.
 */
public class MongodbServer {
    private String path;
    private  Root root;
    private DataBase currentDataBase;
    private Map<String,DataBase> cachMap;
    private Logger logger = Logger.getLogger(MongodbServer.class);
    //private IMDataBaseService dataBaseService;

    public void init(String path){
        this.path = path;
        File file = new File(path);
        if(!file.exists()){
            try {
                initXml();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        cachMap = new HashMap();

        List<DataBase> databases = loadXmlDataBase();
        for (DataBase db : databases) {
            logger.debug("db name:"+db.getName());
            cachMap.put(db.getName(),db);
        }
        //dataBaseService = new MDataBaseService(root.getDataBases());
        //dataBaseService = new MDataBaseService(root);
    }

    public void initXml() throws IOException {
        Document doc = DocumentHelper.createDocument();
        Element databases =doc.addElement("databases");
        Element database = databases.addElement("database");
        database.addAttribute("name","system");

        PrintWriter pw = null;
        try {
            pw = new PrintWriter(this.path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        XMLWriter xw = new XMLWriter(pw);
        xw.write(doc);
        xw.flush();
        xw.close();

    }

    public List<DataBase> loadXmlDataBase(){
        File myXML = new File(path);
        SAXReader reader = new SAXReader();
        try {
            Document document =reader.read(myXML);
            Element rootElement = document.getRootElement();
            root = new Root();
            Iterator it = rootElement.elementIterator();
            while(it.hasNext()){
                Element node = (Element)it.next();
                root.loadXmlDataBase(node);
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return root.getDataBases();
    }

    public void witeXmlDataBase() throws IOException {
        Document doc = DocumentHelper.createDocument();
        root.witeXmlDataBase(doc);
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(this.path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        XMLWriter xw = new XMLWriter(pw);
        xw.write(doc);
        xw.flush();
        xw.close();
    }

    public IMDataBaseService useDataBase(String name){
        currentDataBase = cachMap.get(name);
        if(currentDataBase == null){
            currentDataBase = new DataBase(name);
            root.addChild(currentDataBase);
            cachMap.put(name,currentDataBase);
        }
        // dataBaseService.setCurrentDb(currentDataBase);
        IMDataBaseService dataBaseService =  new MDataBaseService(root,currentDataBase);
        return dataBaseService;
    }

    public void showDataBase(){
        List<DataBase> list = root.getDataBases();
        for (DataBase db: list ) {
            logger.debug(db.getName());
        }
    }

    public boolean createDataBase(String name) {
       DataBase db = cachMap.get(name);
        if(db!=null){
            logger.debug("已经存在同名数据库");
            return false;
        }
        db = new DataBase(name);
        root.addChild(db);
        cachMap.put(name,db);
        return true;
    }

    public boolean dropDataBase(String name) {
        cachMap.remove(name);
        root.removeChild(name);

        return true;
    }

   /* public  IMDataBaseService createdbService(){
      return  new MDataBaseService(root);
    }*/




    public static void main(String args[]) {
        MongodbServer server = new MongodbServer();
        server.init("D:/mongodb/text.xml");
        server.showDataBase();

        IMDataBaseService fool = server.useDataBase("fool");
        fool.createCollection("user1");
        fool.createCollection("user2");
        Collection person = fool.userCollection("person");
        List<Collection> foolCols = fool.showCollection();

        //dataBaseService.
        Map d = new HashMap();
        d.put("_id","14");
        d.put("name","wang124");
        person.insert(d);
        Map d2 = new HashMap();
        d2.put("_id","15");
        d2.put("name","wang123455");
        person.insert(d2);

        Collection user1 = fool.userCollection("user1");
        Map u1 = new HashMap();
        u1.put("_id","1");
        u1.put("name","wang123455");
        user1.insert(u1);
        try {
            server.witeXmlDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
